package com.jiangsong.batch.abst;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.ChunkListener;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemProcessor;

@Slf4j
public abstract class FeeAbstractItemProcessor<I, O> implements ItemProcessor<I, O>, ChunkListener, StepExecutionListener {

    public abstract O doBatchService(I item);


    @Override
    public O process(I item) throws Exception {
        try {
            this.doBeforeProcess(item);
            O result = this.doBatchService(item);
            this.doAfterProcess(item);
            return result;
        } catch (Exception e) {
            this.onProcessError(item, e);
        }
        return null;
    }


    public void doBeforeProcess(I item) {

    }

    public void doAfterProcess(I item) {

    }

    public void onProcessError(I item, Exception e) throws Exception {
        throw e;
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        log.info("before step, register stepExecution threadLocal");
        StepSyncManager.register(stepExecution);
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        log.info("after step, release stepExecution threadLocal");
        StepSyncManager.release();
        return null;
    }
}
